﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Inventory;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Inventory
{
    public class UpdateInventoryHandler : IRequestHandler<UpdateInventoryCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateInventoryHandler> logger;

        public UpdateInventoryHandler(DatabaseContext db,IMapper mapper,ILogger<UpdateInventoryHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdateInventoryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var model=db.SqlSugar.Queryable<InventorysModel>().Where(x=>x.InventoryId==request.InventoryId).First();
            model = mapper.Map(request, model);
            int r = await db.SqlSugar.Updateable(model).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "库存盘点修改成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "库存盘点修改失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
